package rjeutsky.database.jpa;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import rjeutsky.database.jpa.models.JPASubscription;
import rjeutsky.database.jpa.models.JPAUser;
import rjeutsky.models.Subscription;

public class JPASubscriptionRepository extends BaseCRUDDomainRepository<Subscription> {

	public JPASubscriptionRepository(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
	
	@Override
	public List<Subscription> query() throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Subscription> subscriptions =  JPASubscription.getSubscriptions(session.createQuery("from JPASubscription").list());
		
		session.getTransaction().commit();
		session.close();
		
		return subscriptions;
	}

	@Override
	public void create(Subscription item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPASubscription subscription = new JPASubscription();
		subscription.setUser((JPAUser) session.get(JPAUser.class, item.getUserId()));
		session.save(subscription);
		item.setId(subscription.getId());
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public Subscription read(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		Subscription subscription = null;
		
		JPASubscription jpaSubscription = (JPASubscription) session.get(JPASubscription.class, id);
		if (jpaSubscription != null) {
			subscription = jpaSubscription.getSubscription();
		}
		
		session.getTransaction().commit();
		session.close();
		return subscription;
	}

	@Override
	public void update(Subscription item) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPASubscription subscription = JPASubscription.getJPASubscription(session, item);
		if (subscription != null) {
			subscription.setUser((JPAUser) session.get(JPAUser.class, item.getUserId()));
		}
		
		session.getTransaction().commit();
		session.close();
	}

	@Override
	public void delete(long id) throws SQLException {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		JPASubscription subscription = (JPASubscription) session.get(JPASubscription.class, id);
		if (subscription != null) {
			session.delete(subscription);
		}
		
		session.getTransaction().commit();
		session.close();
	}

}
